/*  Copyright 2010 princehaku
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  Created on : 2010-11-16, 23:19:19
 *  Author     : princehaku
 */
package net.techest.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**HTTP连接类
 * 带cookie 可以使用GET和POST
 * @author princehaku
 */
public class HttpClient {
	
	public enum REQ_TYPE{
		POST,GET,HEAD
	};

    private HttpURLConnection httpConn = null;
    
    private URL turl;
    
    private REQ_TYPE requestType;
    
    private String postString;
    
    public URL getUrl(){
    	return this.turl;
    }
    /**设置请求的url
     * 
     * @param url
     * @throws MalformedURLException
     */
    public void setUrl(String url) throws MalformedURLException{
    	turl = new URL(url);
        System.out.println("URL SET :"+url);
    }
    /**设置请求类型
     * 
     * @param req_type
     */
    public void setRequestType(REQ_TYPE req_type){
			this.requestType=req_type;
    }
    
    public HttpClient() {
      
    }

    /** 存放cookie
     */
    private String cookieString = "";

	private Map<String, List<String>> responseHeader;

	private String responseMessage;
	
	
    /**清空cookie
     *
     */
    public void clearCookie(){
        this.cookieString="";
    }

    public void setCookieString(String cookieString) {
        this.cookieString = cookieString;
    }

    public String getCookieString() {
        return cookieString;
    }

	public String getRequestType() {
		return requestType.toString();
	}
	
	public String getPostString() {
		return postString;
	}
	
	public void setPostString(String postString) {
		this.postString = postString;
	}
    /**
     *
     * @param url
     *            提交地址
     */
    @SuppressWarnings("finally")
    public byte[] exec() throws Exception {

        String line = "";

        StringBuffer content =new StringBuffer();

        try {
            httpConn = (HttpURLConnection) turl.openConnection();
            httpConn.setConnectTimeout(30000);
            httpConn.setReadTimeout(30000);
            httpConn.setRequestMethod("GET");
            httpConn.setRequestProperty("Host", turl.getHost());
            httpConn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1");
            httpConn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            httpConn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.5");
            httpConn.setRequestProperty("Accept-Charset", "gbk,GB2312;q=0.7,*;q=0.7");
            if (!(getCookieString().equals(""))) {
                // 晕死..
                httpConn.setRequestProperty("Cookie", "" + getCookieString()+ ";");
                // System.out.print("发送cookie======="+Inc.cookieString);
            }
            httpConn.setRequestProperty("Keep-Alive", "off");
            httpConn.setRequestProperty("Cache-Control", "max-age=0");
            
            if(this.requestType.equals(REQ_TYPE.POST)){
                System.out.println("传递POST值");
	            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	            httpConn.setRequestProperty("Content-Length", String.valueOf(getPostString().length()));
	            httpConn.setDoOutput(true);
	            httpConn.setDoInput(true);
	            OutputStreamWriter out = new OutputStreamWriter(httpConn.getOutputStream());
	            out.write(getPostString() );
	            out.close();
            }
            
            System.out.println("Content Length:"+httpConn.getContentLength());
            
            InputStream uurl;
            uurl = httpConn.getInputStream();
            //放到header去
            this.responseHeader=httpConn.getHeaderFields();
            //放到mseega
            this.responseMessage="HTTP/1.0 "+httpConn.getResponseCode()+" "+httpConn.getResponseMessage();
            
            if (httpConn.getHeaderField("Set-Cookie") != null) {
                String set_Cookie = httpConn.getHeaderField("Set-Cookie");
                System.out.println("得到cookie"+set_Cookie);
                setCookieString(set_Cookie.substring(0, set_Cookie.indexOf(";")));
            }
            
            BufferedReader br = new BufferedReader(new InputStreamReader(uurl));
            
            while (line != null) {
                line = br.readLine();
                if (line != null) {
                    content.append(line.toString());
                }
            }

        } catch (Exception e) {
            throw e;
        } finally {
            // 关闭连接
            httpConn.disconnect();
            return content.toString().getBytes();
        }
    }
    
	public Map<String, List<String>> getResponseHeader() {
		return this.responseHeader;
	}
	public String getResponseMessage() {
		return this.responseMessage;
	}
}
